import os

import pyshark
import threading
import time
from collections import defaultdict
#VMware Network Adapter VMnet8

"""
实时抓取 62244 端口的所有 TCP/UDP 报文
保存为 pcap 并同时打印简要信息
"""
os.environ.setdefault("TSHARK_PATH", r"D:\Wireshark\tshark.exe")

import pyshark
import datetime as dt
IFACE   = 'VMware Network Adapter VMnet8'          # ← 改成你本机要监听的接口
PORT    = 63061
PCAP    = f'port_{PORT}_{dt.datetime.now():%Y%m%d_%H%M%S}.pcap'

# 1. 实时抓包
capture = pyshark.LiveCapture(
    interface=IFACE,
    bpf_filter=f'tcp port {PORT} or udp port {PORT}',   # Berkeley Packet Filter
    output_file=PCAP
)

print(f'开始监听接口 {IFACE} 的 {PORT} 端口，Ctrl-C 停止...\n')

# 2. 逐包回调
for pkt in capture.sniff_continuously():
    try:
        proto = pkt.transport_layer          # 'TCP' or 'UDP'
        src_addr = pkt.ip.src
        dst_addr = pkt.ip.dst
        src_port = pkt[pkt.transport_layer].srcport
        dst_port = pkt[pkt.transport_layer].dstport
        length = pkt.length
        print(f'{proto} {src_addr}:{src_port} -> {dst_addr}:{dst_port}  {length} bytes')
    except AttributeError:
        # 非 IPv4 或没有传输层字段时跳过
        continue